package com.sljy.hzk.ui.exam;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.bumptech.glide.Glide;
import com.example.api.InjectParam;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sljy.hzk.R;
import com.sljy.hzk.animation.AnimationManager;
import com.sljy.hzk.annotation.ActivityInfo;
import com.sljy.hzk.base.BaseActivity;
import com.sljy.hzk.base.UserInfo;
import com.sljy.hzk.entity.ExamAnswerEntity;
import com.sljy.hzk.entity.ExamErrDetailEntity;
import com.sljy.hzk.entity.ExamInfosEntity;
import com.sljy.hzk.entity.ExamSubjectEntity;
import com.sljy.hzk.entity.ExamSubjectOptionEntity;
import com.sljy.hzk.entity.ExamSubmitEntity;
import com.sljy.hzk.entity.UserEntity;
import com.sljy.hzk.net.BaseCallBack;
import com.sljy.hzk.net.HttpHeper;
import com.sljy.hzk.net.service.ExamService;
import com.sljy.hzk.room.AppDataBase;
import com.sljy.hzk.room.dao.TaskDao;
import com.sljy.hzk.ui.task.TaskExecuteActivity__JumpCenter;
import com.sljy.hzk.view.CustomStateText;
import com.sljy.hzk.view.ExamChoiceLayout;
import com.sljy.hzk.view.NoScrollViewPager;
import com.tkk.api.RxEventProcessor;
import com.tkk.api.annotation.Recipient;
import com.trello.rxlifecycle2.android.ActivityEvent;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindDrawable;
import butterknife.BindView;
import butterknife.OnClick;
import cn.iwgang.countdownview.CountdownView;

import static com.sljy.hzk.annotation.ActivityInfo.TITLE_TWO_LEVEL;

@ActivityInfo(layout = R.layout.activity_exam_do,isShowActionBar = true, title = "考试")
public class ExamDoActivity extends BaseActivity {
    @InjectParam
    String examId;
    @BindView(R.id.tv_finsh)
    TextView tvFinsh;
//    @BindView(R.id.countdown_view)
//    CountdownView countdownView;
    @BindView(R.id.tv_up)
    ImageButton tvUp;
    @BindView(R.id.viewpager)
    NoScrollViewPager viewpager;
    @BindView(R.id.img_next)
    ImageView imgNext;
    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindDrawable(R.drawable.shape_task_bg)
    Drawable drawableLast;
    @BindDrawable(R.drawable.shape_task_bg)
    Drawable drawableLastCan;
    @BindDrawable(R.drawable.shape_task_bg)
    Drawable drawableNext;
    @BindDrawable(R.drawable.shape_task_bg)
    Drawable drawableNextCan;
    @BindView(R.id.progressBar)
    ProgressBar progressBar;
    private List<String> trueAnswer;
    private List<ExamSubjectEntity> subjectEntityList = new ArrayList<>();
    MyPagerAdapter adapter;
    private int nowPos = 0;
    UserEntity user;
    List<ExamErrDetailEntity.SubjectBean> qustionList;
    @SuppressLint("SetTextI18n")
    @Override
    protected void init() {
       // ExamDoActivity__JumpCenter.bind(this);
        RxEventProcessor.get().bind(this);
        trueAnswer = new ArrayList<String>();
        imgBack.setVisibility(View.GONE);
        imgNext.setVisibility(View.GONE);
        user = UserInfo.getUserInfo();
        viewpager.setScroll(false);
        adapter = new MyPagerAdapter();
        viewpager.setAdapter(adapter);
        Gson json = new Gson();
        Intent intent = getIntent();
        ExamInfosEntity data = json.fromJson(intent.getStringExtra("ExamInfosEntity"), new TypeToken<ExamInfosEntity>() {}.getType());
        examId = intent.getStringExtra("ExamId");
        qustionList = json.fromJson(intent.getStringExtra("SaveQu"), new TypeToken< List<ExamErrDetailEntity.SubjectBean>>() {}.getType());
        setTitle(data.getExamName());
        loadData(data);
//        HttpHeper.get().create(ExamService.class)
//                .getExamInfos(examId,user.getName(), user.getIdCard(),user.getUserId())
//                .compose(this.bindUntilEvent(ActivityEvent.DESTROY))
//                .compose(getThread())
//                .subscribe(new BaseCallBack<ExamInfosEntity>(this) {
//                    @Override
//                    public void onCallBackSuccess(ExamInfosEntity data) {
//                        subjectEntityList.clear();
//                        setTitle(data.getExamName());
//                        countdownView.setVisibility(View.GONE);
//                        //countdownView.start(data.getTime() * 1000);
//                        subjectEntityList.addAll(data.getList());
//                        tvFinsh.setText("第1/" + subjectEntityList.size() + "题");
//                        setImgRes();
//                        adapter.notifyDataSetChanged();
//                    }
//
//                    @Override
//                    public void onFail(String mes) {
//                        showToast(mes);
//                    }
//                });
        viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                nowPos = position;
                int itemPos = position + 1;
                setImgRes();
                if(trueAnswer.size() > 0)
                    tvFinsh.setText(Html.fromHtml("正确答案 : <font color='red'>" + trueAnswer.get(position)+ "</font>" ));
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        /**
         * 时间到
         */
//        countdownView.setOnCountdownEndListener(new CountdownView.OnCountdownEndListener() {
//            @Override
//            public void onEnd(CountdownView cv) {
//                checkAndUp(true);
//            }
//        });
        tvUp.setOnTouchListener(new View.OnTouchListener(){
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(DoEffect(v,event)){
                    checkAndUp(false);
                }
                return false;
            }
        });

    }

    private void loadData(ExamInfosEntity data){
        if(data == null){
            showToast("数据错误");
            return;
        }

        subjectEntityList.clear();
        setTitle(data.getExamName());
       // countdownView.setVisibility(View.GONE);
        //countdownView.start(data.getTime() * 1000);
        subjectEntityList.addAll(data.getList());
        tvFinsh.setText(Html.fromHtml("已答 : <font color='green'>" + 0 + "</font>/" + subjectEntityList.size()));
        setImgRes();

        //加入答案
        if(qustionList.size() > 0){
            for (ExamSubjectEntity examSubjectEntity : subjectEntityList) {
                for( ExamErrDetailEntity.SubjectBean qua : qustionList){
                    if(examSubjectEntity.getId() == qua.getQueId()){
                        for (ExamSubjectOptionEntity examSubjectOptionEntity : examSubjectEntity.getList()) {
                            if(examSubjectOptionEntity.getValue().equals(qua.getAnswer())){
                                examSubjectOptionEntity.setCheck(true);
                                trueAnswer.add(qua.getTrueAnswer());
                            }
                        }
                    }
                }
            }
            tvUp.setVisibility(View.GONE);
            tvFinsh.setText(Html.fromHtml("正确答案 : <font color='red'>" + trueAnswer.get(0)+ "</font>" ));
            progressBar.setVisibility(View.GONE);

        }

        adapter.notifyDataSetChanged();
    }

    /**
     * 设置进度条
     * */
    private void setProgressState(int p){
        float f =  (float) p/(float)subjectEntityList.size()*100.0f;
        int f2 = Math.round(f);
        progressBar.setProgress(f2);
    }

    /**
     * 交卷
     */
//    @OnClick({R.id.tv_up})
//    public void up() {
//        checkAndUp(false);
//
//    }
    @Recipient(tag = "examItemChange")
    public void itemChange() {
        int p = getProgressNum();
        tvFinsh.setText(Html.fromHtml("已答 : <font color='green'>" + p + "</font>/" + subjectEntityList.size()));
        setProgressState(p);
    }

    /**
     * 获取进度数量
     * */
    private int getProgressNum(){
        int num = 0;
        for (ExamSubjectEntity examSubjectEntity : subjectEntityList) {
            ExamAnswerEntity answerEntity = new ExamAnswerEntity(examSubjectEntity.getSort(),examSubjectEntity.getId(),examSubjectEntity.getTitle());
            for (ExamSubjectOptionEntity examSubjectOptionEntity : examSubjectEntity.getList()) {
                if (examSubjectOptionEntity.isCheck()) {
                    num++;
                    break;
                }
            }
        }
        return num;
    }

    private void checkAndUp(boolean timeOut) {
        int num = 0;
        int firstPos = -1;
        int index = 0;
        boolean inNext = false;
        //答案集合
        List<ExamAnswerEntity> answerEntityList = new ArrayList<>();
        for (ExamSubjectEntity examSubjectEntity : subjectEntityList) {
            index++;
            inNext = false;
            ExamAnswerEntity answerEntity = new ExamAnswerEntity(examSubjectEntity.getSort(),examSubjectEntity.getId(),examSubjectEntity.getTitle());
            for (ExamSubjectOptionEntity examSubjectOptionEntity : examSubjectEntity.getList()) {
                if (examSubjectOptionEntity.isCheck()) {
                    num++;
                    inNext = true;
                    answerEntity.setAnswer(examSubjectOptionEntity.getValue());
                    break;
                }
            }
            if(!inNext){
                if(firstPos == -1 )
                    firstPos = index;
            }

            answerEntityList.add(answerEntity);
        }

        Gson gson = new Gson();
        String json = gson.toJson(answerEntityList);
        if(timeOut){
            showToast("时间到，自动交卷");
            submit(json);
        }else {
            if (num == subjectEntityList.size()) {
                submit(json);
                return;
            }else{
                //跳转去没有做得题
                viewpager.setCurrentItem(firstPos-1, true);
                showToast("请填写所有答案后再进行交卷");
            }
//            new MaterialDialog.Builder(this)
//                    .content("当前只完成" + num + "/" + subjectEntityList.size() + ",确认交卷吗？")
//                    .positiveText("确定")
//                    .onPositive((dia, v) -> {
//                        submit(json);
//                    }).negativeText("取消")
//                    .show();
        }
    }

    /**
     * 交卷-数据上传
     * @param answerJson
     */
    private void  submit(String answerJson){
        HttpHeper.get().create(ExamService.class)
                .submit(examId,user.getCpId(),answerJson)
                .compose(this.bindUntilEvent(ActivityEvent.DESTROY))
                .compose(getThread())
                .subscribe(new BaseCallBack<ExamSubmitEntity>(this) {
                    @Override
                    public void onCallBackSuccess(ExamSubmitEntity data) {
                        shoiEndDialog(data);
                    }
                });
    }

    private void shoiEndDialog( ExamSubmitEntity data){
        Dialog dialog=new Dialog(this);//可以在style中设定dialog的样式
        dialog.setContentView(R.layout.exam_end_dialog);
        WindowManager.LayoutParams lp= dialog.getWindow().getAttributes();
        lp.gravity= Gravity.CENTER;
        lp.height= WindowManager.LayoutParams.WRAP_CONTENT;
        lp.width= WindowManager.LayoutParams.MATCH_PARENT;
        TextView tvMsg=(TextView)dialog.getWindow().findViewById(R.id.scroe);
        tvMsg.setText(data.getTotalScore()+"分");
        TextView tvState =(TextView)dialog.getWindow().findViewById(R.id.stateText);
        if(!data.isPass()){
            tvState.setText("不合格");
            tvMsg.setBackgroundResource(R.drawable.exam_fail);
        }else
            tvState.setText("合格");
        ImageButton btOk=(ImageButton)dialog.getWindow().findViewById(R.id.yBtn);
        btOk.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {
                finish();
            }
        });
        dialog.getWindow().setAttributes(lp);
        //设置该属性，dialog可以铺满屏幕
        dialog.getWindow().setBackgroundDrawable(null);
        dialog.show();
    }


    @OnClick(R.id.img_next)
    public void onImgNextClicked() {
        if (nowPos != subjectEntityList.size() - 1) {
            viewpager.setCurrentItem(nowPos + 1, true);
        }

    }

    @OnClick(R.id.img_back)
    public void onImgBackClicked() {
        if (nowPos != 0) {
            viewpager.setCurrentItem(nowPos - 1, true);
        }
    }

    /**
     * 根据位置设置，上一项，下一项的背景图
     */
    private void setImgRes() {
        imgBack.setVisibility(nowPos == 0 ? View.GONE : View.VISIBLE);
        imgNext.setVisibility(nowPos == subjectEntityList.size() - 1 ? View.GONE : View.VISIBLE);
        //imgBack.setImageDrawable(nowPos == 0 ? drawableLast : drawableLastCan);
        //imgNext.setImageDrawable(nowPos == subjectEntityList.size() - 1 ? drawableNext : drawableNextCan);
    }

    private boolean DoEffect(View view, MotionEvent event){
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                AnimationManager.Instance().DoScaleAction(view, 1.0f,1.05f,1.0f,1.05f,50);
                return false;
            case  MotionEvent.ACTION_UP:
                AnimationManager.Instance().DoScaleAction(view, 1.05f,1.0f,1.05f,1.0f,50);
                return true;
        }
        return false;
    }

    @Override
    protected void removeEvent(){
        RxEventProcessor.get().unBind(this);
    }


    public class MyPagerAdapter extends PagerAdapter {
        @Override
        public int getCount() {
            return subjectEntityList.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @SuppressLint("SetTextI18n")
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View view = LayoutInflater.from(ExamDoActivity.this).inflate(R.layout.layout_exam, container, false);
            TextView tvSubject = view.findViewById(R.id.tv_subject);
            ImageView imgSubject = view.findViewById(R.id.img_subject);
            ExamChoiceLayout examChoiceLayout = view.findViewById(R.id.exam_chose_layout);
            int itemPos = position + 1;
            ExamSubjectEntity data = subjectEntityList.get(position);
            tvSubject.setText(itemPos + "." + data.getTitle());
            if (TextUtils.isEmpty(data.getImg())) {
                imgSubject.setVisibility(View.GONE);
            } else {
                //转义
                String imgPath = data.getImg().replace("\\","/");
                Glide.with(ExamDoActivity.this).load(imgPath).into(imgSubject);
            }
            examChoiceLayout.bindOption(data.getList());
            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

    }
}
